Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

Python Functions → def Keyword

Python Functions

def Keyword

Python's `def` Keyword and Function Concepts

In Python, functions are reusable blocks of code designed to perform specific tasks. They enhance code readability, organization, and efficiency by avoiding repetition. The `def` keyword is the cornerstone of defining functions.

Basic Structure of a Python Function

Basic Structure of a Python Function def function_name(parameter1, parameter2, ...): """Docstring: Briefly describes the function's purpose.""" # Function body: Code that performs the task # ... return value # Optional: Returns a value
Let's break this down: ⮚ `def` Keyword: This keyword signals the start of a function definition. ⮚ `function_name`: You choose a descriptive name for your function (following Python's naming conventions – lowercase with underscores for readability). ⮚ `(parameter1, parameter2, ...)`: These are input values (optional). Parameters act as placeholders for data the function will use. They're separated by commas. ⮚ `"""Docstring"""`: This is a multi-line string (triple quotes) that explains what the function does. It's crucial for documentation and understanding the function's purpose. ⮚ `Function body`: This is where the actual code that performs the function's task resides. It's indented (usually four spaces) to indicate it's part of the function. ⮚ `return value`: (Optional) The `return` statement specifies the value the function sends back after execution. If omitted, the function implicitly returns `None`.

Examples

1. Simple Function (No Parameters, No Return Value)
Python function calling example def greet(): """Prints a greeting message.""" print("Hello, world!") greet() # Calling the function

Output

Hello, world!
This function simply prints a message to the console. It doesn't take any input and doesn't return anything.
2. Function with Parameters and Return Value
Python Function with Parameters and Return Value example def add_numbers(x, y): """Adds two numbers and returns the sum.""" sum = x + y return sum result = add_numbers(5, 3) # Calling the function with arguments print(f"The sum is: {result}")

Output

8
This function takes two numbers as input (`x` and `y`), calculates their sum, and returns the result.
3. Function with Default Parameter Values
Python Function with Default Parameter Values example def greet_person(name, greeting="Hello"): """Greets a person with a customizable greeting.""" print(f"{greeting}, {name}!") greet_person("Alice") greet_person("Bob", "Good morning")

Output

Hello, Alice! Good morning, Bob!
Here, `greeting` has a default value of "Hello". If you don't provide a greeting when calling the function, it uses the default.
4. Function with Variable Number of Arguments
Python Function with Variable Number of Arguments def sum_all_numbers(*args): """Calculates the sum of all numbers passed as arguments.""" total = 0 for number in args: total += number return total result = sum_all_numbers(1, 2, 3, 4, 5) print(f"The sum is: {result}")

Output

15
The `*args` syntax allows the function to accept any number of positional arguments, which are packed into a tuple named `args`.
5. Function with Keyword Arguments
Python Function with Keyword Arguments def describe_pet(animal_type, pet_name, age=None): """Displays information about a pet.""" print(f"\ I have a {animal_type}.") print(f"My {animal_type}'s name is {pet_name.title()}.") if age: print(f"My {animal_type} is {age} years old.") describe_pet(animal_type='hamster', pet_name='harry') describe_pet(pet_name='willie', animal_type='dog', age=3)

Output

I have a hamster. My hamster's name is Harry. I have a dog. My dog's name is Willie. My dog is 3 years old.
Keyword arguments allow you to specify argument names when calling a function, making the code more readable and less prone to errors. The order doesn't matter when using keyword arguments.

Tutorials